import { isArray } from "~/utils/tool";

export const useClientRequest = (url, opts) => {
  const token = useCookie("token");
  const runtimeConfig = useRuntimeConfig();

  const defaultOptions = {
    baseURL: runtimeConfig.public.apiBase,
    onRequest({ options }) {
      options.headers = options.headers || {};
      if (token.value) {
        options.headers.Authorization = "Bearer " + token.value;
      }
    },
    onResponse({ response }) {
      if (+response.status === 200 && +response._data.code !== 0) {
        ElMessage.error(response._data.msg);
      }
    },
    onResponseError({ response }) {
      ElMessage.error(
        isArray(response._data.data.msg)
          ? response._data.data.msg[0]
          : response._data.data.msg
      );
    },
  };

  return $fetch(url, { ...defaultOptions, ...opts });
};
